//
//  UIView+Loading.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/12/3.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "UIView+Loading.h"

#import "BCustomLoadingHUD.h"

#import "BCActivityIndicatorHUD.h"

static NSInteger BCustomLoadingHUDTag = 100100;
static NSInteger BCActivityIndicatorHUDTag = 101010;

@implementation UIView (Loading)

#pragma mark - custom
/**
 insets = UIEdgeInsetsZero
 */
- (void)bc_showLoading {
    [self bc_showLoadingInsets:UIEdgeInsetsZero];
}
- (void)bc_showLoadingInsets:(UIEdgeInsets)insets {
    [self bc_hiddenLoading];
    //
    BCustomLoadingHUD *hud = [self viewWithTag:BCustomLoadingHUDTag];
    if (!hud) {
        hud = [BCustomLoadingHUD new];
        hud.tag = BCustomLoadingHUDTag;
        [self addSubview:hud];
        [hud mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self).offset(insets.top);
            make.left.mas_equalTo(self).offset(insets.left);
            make.width.mas_equalTo(self).offset(-insets.left-insets.right);
            make.height.mas_equalTo(self).offset(-insets.bottom-insets.top);
        }];
        [self layoutIfNeeded];
    }
    [hud.loadingView startLoading];
}
- (void)bc_hiddenLoading {
    BCustomLoadingHUD *hud = [self viewWithTag:BCustomLoadingHUDTag];
    if (hud) {
        [hud.loadingView stopLoading];
        [hud removeFromSuperview];
    }
}


#pragma mark - ActivityIndicatorView

- (void)bc_showActivityIndicatorBackgroundColor:(UIColor *)backgroundColor insets:(UIEdgeInsets)insets activityIndicatorViewStyle:(UIActivityIndicatorViewStyle)style {
    [self bc_hiddenActivityIndicator];
    BCActivityIndicatorHUD *hud = [BCActivityIndicatorHUD new];
    hud.tag = BCActivityIndicatorHUDTag;
    hud.backgroundColor = backgroundColor;
    hud.activityIndicatorViewStyle = style;
    [self addSubview:hud];
    [hud mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self).offset(insets.top);
        make.left.mas_equalTo(self).offset(insets.left);
        make.width.mas_equalTo(self).offset(-insets.left-insets.right);
        make.height.mas_equalTo(self).offset(-insets.bottom-insets.top);
    }];
    [self layoutIfNeeded];
    [hud.activityIndicatorView startAnimating];
}

- (void)bc_showActivityIndicatorBackgroundColor:(UIColor *)backgroundColor insets:(UIEdgeInsets)insets {
    [self bc_showActivityIndicatorBackgroundColor:backgroundColor insets:insets activityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
}
- (void)bc_hiddenActivityIndicator {
    BCActivityIndicatorHUD *hud = [self viewWithTag:BCActivityIndicatorHUDTag];
    if (hud) {
        [hud.activityIndicatorView stopAnimating];
        [hud removeFromSuperview];
    }
}

@end
